import { init, h } from 'snabbdom'
import _orderBy from 'lodash/orderBy'
import _flatten from 'lodash/flatten'

import eventListeners from 'snabbdom/modules/eventlisteners'

let oldVnode = null

let data = [
    {
        id: 1,
        name: '齐天大圣',
        desc: '你猜，这是一部很好看的电影？'
    },
    {
        id: 2,
        name: '葫芦娃',
        desc: '这是一部很好看的电影'
    },
    {
        id: 3,
        name: 'joker',
        desc: '世界在慢慢的把人变成小丑'
    }
]

function exchangeH(data) {
    return data.map(item=> {
        return h('li', [
            h('div', item.id),
            h('div', item.name),
            h('div', item.desc)
        ])
    })
}

function onSort(key = 'id') {
    data = _orderBy(data, [key], ['asc']);
    renderDom(data)
}

function onAdd () {
    const randomMovie = {
        id: Math.floor((Math.random()*100)+1),
        name: Math.floor((Math.random()*100)+1),
        desc: Math.floor((Math.random()*100)+1),
    }
    data.unshift(randomMovie)
    renderDom(data)
}

function getActions () {
    return h('div.sort', [
        h('div', 'sort: '),
        h('button', {
            on: {
                click: ()=>onSort('id')
            }
        }, 'rank'),
        h('button', {
            on: {
                click: ()=>onSort('name')
            }
        }, 'title'),
        h('button', {
            on: {
                click: ()=>onSort('desc')
            }
        }, 'desc'),
        h('button', {
            on: {
                click: onAdd
            }
        }, 'add'),
    ])
}

function renderDom(data) {
    const hMovieList = exchangeH(data)
    const actions = getActions()

    let patch = init([eventListeners])

    let vnode = h('ul#container',  _flatten([actions, hMovieList]))
    if(oldVnode) {
        oldVnode = patch(oldVnode, vnode)
        return
    }
    let app = document.querySelector('#app')
    oldVnode = patch(app, vnode)
}

renderDom(data)

